package com.yunxin.core.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.admin.mapper.AdminUserMapper;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.customer.domain.CustomerChange;
import com.yunxin.core.customer.domain.CustomerChangeUrl;
import com.yunxin.core.customer.domain.CustomerInfo;
import com.yunxin.core.customer.domain.CustomerTag;
import com.yunxin.core.customer.dto.OperationCustomerChangeDto;
import com.yunxin.core.customer.mapper.CustomerChangeUrlMapper;
import com.yunxin.core.customer.mapper.CustomerInfoMapper;
import com.yunxin.core.customer.mapper.CustomerTagMapper;
import com.yunxin.core.customer.service.CustomerChangeService;
import com.yunxin.core.customer.mapper.CustomerChangeMapper;
import com.yunxin.core.customer.service.CustomerChangeUrlService;
import com.yunxin.core.customer.service.CustomerInfoService;
import com.yunxin.core.customer.service.CustomerTagService;
import com.yunxin.core.customer.vo.CustomerChangeInfoVo;
import com.yunxin.core.customer.vo.CustomerCommonVo;
import com.yunxin.core.customer.vo.CustomerInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【customer_change(客户流转表)】的数据库操作Service实现
 * @createDate 2024-05-22 17:11:04
 */
@DS("crm")
@Service
public class CustomerChangeServiceImpl extends ServiceImpl<CustomerChangeMapper, CustomerChange>
        implements CustomerChangeService {

    @Autowired
    private CustomerTagMapper customerTagMapper;

    @Autowired
    private CustomerTagService customerTagService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private CustomerChangeMapper customerChangeMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private CustomerChangeUrlService customerChangeUrlService;

    @Autowired
    @Lazy
    private AdminUserService adminUserService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean customerChange(OperationCustomerChangeDto dto) {
        CustomerInfo info = customerInfoService.getById(dto.getCustomerId());
        if (info.getSalesmanId().intValue()==dto.getChangeUserId()){
            throw new BusinessException("该客户已分配给该业务员");
        }
        List<CustomerTag> list = new ArrayList<>();
        try {
            if(CollUtil.isNotEmpty(dto.getTagIds())){
                // 先删除客户所有表签
                customerTagMapper.delete(new LambdaQueryWrapper<CustomerTag>().eq(CustomerTag::getCustomerInfoId, dto.getCustomerId()));
                // 新增客户标签
                for (Long tagId : dto.getTagIds()) {
                    CustomerTag customerTag = new CustomerTag();
                    customerTag.setCustomerInfoId(dto.getCustomerId().longValue());
                    customerTag.setTagInfoId(tagId);
                    list.add(customerTag);
                }
                customerTagService.saveBatch(list);
            }
            // 修改客户业务员id
            CustomerChange change = new CustomerChange();

            change.setAgoTelephonerId(info.getTelephonerId());
            change.setAgoUserId(info.getSalesmanId());
            if (ObjectUtils.isEmpty(info)){
                throw new BusinessException("未找到资源");
            }
            info.setSalesmanId(dto.getChangeUserId());
            info.setTelephonerId(dto.getTelephonerId());
            info.setRunReason(dto.getChangeReason());
            //info.setSalesmanStatus(0);
            info.setTelephonerStatus(0);
            info.setSource(2);
            info.setSalesmanSource("同事流转");
            customerInfoService.updateById(info);
            // 新增流转记录
            AdminUser adminUser = adminUserMapper.getAdminUser(dto.getOperator());
            change.setCustomerInfoId(dto.getCustomerId().longValue());
            change.setNewUserId(dto.getChangeUserId());
            change.setNewTelephonerId(dto.getTelephonerId());
            change.setType(dto.getChangeType());
            change.setCause(dto.getChangeReason());
            change.setCreator(adminUser.getNickname());
            customerChangeMapper.insert(change);
            // 新增流转附件记录
            if (!ObjectUtils.isEmpty(dto.getAttachmentUrls())){
                CustomerChangeUrl changeUrl = new CustomerChangeUrl();
                changeUrl.setUrls(JSONUtil.toJsonStr(dto.getAttachmentUrls()));
                changeUrl.setCustomerChangeId(change.getId());
                changeUrl.setCreator(adminUser.getNickname());
                customerChangeUrlService.save(changeUrl);
            }
        } catch (Exception e) {
            throw new BusinessException("客户流转失败");
        }
        return true;
    }

    @Override
    public List<CustomerChangeInfoVo> customerChangeInfo(Integer customerId) {
        LambdaQueryWrapper<CustomerChange> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerChange::getCustomerInfoId,customerId).orderByDesc(CustomerChange::getCreateTime);
        List<CustomerChange> list = this.list(queryWrapper);
        if (ObjectUtils.isEmpty(list)){
            return null;
        }
        Set<Integer> userIds=new HashSet<>();
        List<Long> customerChangeIds=new ArrayList<>();
        for (CustomerChange customerChange : list) {
            userIds.add(customerChange.getAgoUserId());
            userIds.add(customerChange.getNewUserId());
            if (!ObjectUtils.isEmpty(customerChange.getAgoTelephonerId())){
                userIds.add(customerChange.getAgoTelephonerId());
            }
            if (!ObjectUtils.isEmpty(customerChange.getNewTelephonerId())) {
                userIds.add(customerChange.getNewTelephonerId());
            }
            customerChangeIds.add(customerChange.getId());
        }
        CustomerInfo customerInfo = customerInfoService.getById(customerId);
        List<AdminUser> adminUsers = adminUserService.listByIds(userIds);
        Map<Integer, String> userMap = adminUsers.stream().collect(Collectors.toMap(AdminUser::getId, obj -> obj.getNickname()));
        LambdaQueryWrapper<CustomerChangeUrl> changeUrlLambdaQueryWrapper=new LambdaQueryWrapper<>();
        changeUrlLambdaQueryWrapper.in(CustomerChangeUrl::getCustomerChangeId,customerChangeIds);
        List<CustomerChangeUrl> customerChangeUrls = customerChangeUrlService.list(changeUrlLambdaQueryWrapper);
        Map<Long, CustomerChangeUrl> changeUrlMap = customerChangeUrls.stream().collect(Collectors.toMap(CustomerChangeUrl::getCustomerChangeId, obj -> obj));
        List<CustomerChangeInfoVo> customerChangeInfoVos=new ArrayList<>();
        for (CustomerChange customerChange : list) {
            CustomerChangeInfoVo customerChangeInfoVo=new CustomerChangeInfoVo();
            customerChangeInfoVo.setCustomerId(customerId);
            customerChangeInfoVo.setCustomerName(customerInfo.getName());
            customerChangeInfoVo.setChangeType(customerChange.getType());
            customerChangeInfoVo.setAgoSalesmanId(customerChange.getAgoUserId());
            customerChangeInfoVo.setAgoSalesmanName(userMap.get(customerChange.getAgoUserId()));
            customerChangeInfoVo.setNewSalesmanId(customerChange.getNewUserId());
            customerChangeInfoVo.setNewSalesmanName(userMap.get(customerChange.getNewUserId()));

            customerChangeInfoVo.setAgoTelephonerId(customerChange.getAgoTelephonerId());
            customerChangeInfoVo.setAgoTelephonerName(userMap.get(customerChange.getAgoTelephonerId()));
            customerChangeInfoVo.setNewTelephonerId(customerChange.getNewTelephonerId());
            customerChangeInfoVo.setNewTelephonerName(userMap.get(customerChange.getNewTelephonerId()));

            customerChangeInfoVo.setChangeReason(customerChange.getCause());
            customerChangeInfoVo.setCreateTime(customerChange.getCreateTime());
            CustomerChangeUrl customerChangeUrl = changeUrlMap.get(customerChange.getId());
            if (!ObjectUtils.isEmpty(customerChangeUrl)&&!ObjectUtils.isEmpty(customerChangeUrl.getUrls())){
                customerChangeInfoVo.setUrls(JSONUtil.toList((String) customerChangeUrl.getUrls(),String.class));
            }
            customerChangeInfoVos.add(customerChangeInfoVo);
        }
        return customerChangeInfoVos;
    }
}




